<template>
  <span>
    <el-button type="text" icon="el-icon-upload" size="mini" @click="export_in">{{ name }}</el-button>
    <el-dialog :title="title" :visible.sync="exportVisible" top="5vh" width="500px" append-to-body>
      <el-upload
        ref="upload"
        :action="action"
        :headers="headers"
        :data="exportData"
        :auto-upload="false"
        :file-list="fileList"
        :limit="limit"
        :before-upload="beforeUpload"
        :on-success="exportSuccess"
        :on-error="exportError"
        :on-exceed="handleExceed"
        drag
        multiple
        accept=".xls,.xlsx"
      >
        <i class="el-icon-upload"/>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过500kb</div>
      </el-upload>
      <div align="right">
        <el-button @click="exportVisible = false">关 闭</el-button>
        <el-button :loading="btnLoad" type="primary" @click="confirmExportIn">确 定</el-button>
      </div>
    </el-dialog>
  </span>
</template>
<script>
import { getToken } from '@/utils/auth'
import SERVER from '@/api/server'
export default {
  name: 'Upload',
  props: {
    url: String,
    model: String,
    title: String,
    name: String,
    limit: Number,
    orderFormObj: Object
  },
  data() {
    return {
      exportVisible: false,
      btnLoad: false,
      exportData: {
        fileName: '',
        errorData: []
      },
      fileList: [],
      headers: {
        Authorization: getToken()
      }
    }
  },
  computed: {
    action() {
      return `${SERVER[this.model]}` + this.url
    }
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传 ${this.limit} 个文件!`)
    },
    // 导入
    export_in() {
      this.exportVisible = true
      this.fileList = []
    },
    // 导入确认
    confirmExportIn() {
      this.$refs['upload'].submit()
    },
    beforeUpload(file) {
      if (file.size > 5242880) {
        this.$message.warning(` ${file.name}不能超过500kb!`)
        return
      }
      if (
        file.type == 'application/vnd.ms-excel' ||
          file.type ==
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ) {
        this.exportData.fileName = file.name
      } else {
        this.$message.warning(` ${file.name}不是Excle文件!`)
      }
    },
    exportSuccess(response, file) {
      this.exportVisible = false
      this.$message({
        type: 'success',
        message: `${file.name}导入成功`
      })
      this.fileList = []
      this.$emit('exportSuccessData', response)
    },
    exportError(response, file) {
      this.exportVisible = false
      this.$message({
        type: 'error',
        message: JSON.parse(response.message).errorData[0].errorMsg
      })
      this.fileList = []
    }
  }
}
</script>

